﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    public partial class ProductConsumeForm : XtraForm
    {
        private string m_CurrentProdNo = "";
        private string m_CurrentMaterial = "";
        private string m_CurrentProductline = "";
        private DateTime m_Start = DateTime.MinValue;
        private DateTime m_End = DateTime.MaxValue;

        private Dictionary<string, string> m_MaterialCrossDic = new Dictionary<string, string>();
        private DataTable m_BindDT = null;

        //类型，0：4500访问SQLServer，1：3800
        private int m_Type = 0;
        public int Type
        {
            set { m_Type = value; }
        }

        private string m_OrderCode ="";
        public string OrderCode
        {
            set { m_OrderCode = value; }
        }

        public ProductConsumeForm()
        {
            InitializeComponent();
        }

        private void ProductConsumeForm_Load(object sender, EventArgs e)
        {
            this.Size = Screen.GetWorkingArea(this).Size;
            this.Location = new Point(0, 0);
            dateEditStart.EditValue = DateTime.Now.Date;
            dateEditEnd.EditValue = DateTime.Now;
            m_Type = int.Parse(ConfigurationManager.AppSettings["MachineType"].ToString());
            this.txtOrderCode.Text = m_OrderCode;
            InitBindDT();
            InitMaterial();
            InitProductLine();
        }

        private void InitBindDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("ProdNo");
            m_BindDT.Columns.Add("Batchno");
            m_BindDT.Columns.Add("MaterialName");
            m_BindDT.Columns.Add("MaterialType");
            m_BindDT.Columns.Add("MAcademic");
            m_BindDT.Columns.Add("MDesign");
            m_BindDT.Columns.Add("MAct");
            m_BindDT.Columns.Add("BatchTime",typeof(DateTime));
            m_BindDT.Columns.Add("StoreNo");
            m_BindDT.Columns.Add("Pdate", typeof(DateTime));
            m_BindDT.Columns.Add("ProductLine");
            m_BindDT.Columns.Add("RecipeValue");
            m_BindDT.Columns.Add("BatchAdd");
        }

        private void InitMaterial()
        {
            try
            {
                if (m_Type == 0 || m_Type == 1)
                {
                    string sql = "select * from MaterialTypeList";
                    DataTable dt = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                    if (dt == null || dt.Rows.Count == 0)
                        return;
                    foreach (DataRow dr in dt.Rows)
                        this.mruEditMaterial.Properties.Items.Add(dr["MaterialName"].ToString().Trim());
                }
                else if (m_Type == 2)
                {
                    //3800无物料对照表，将知道的字段对应的物料做成配置
                    string materialCrossNameStr = ConfigurationManager.AppSettings["MaterialCrossName"].ToString();
                    foreach (string item in materialCrossNameStr.Split(','))
                    {
                        string[] strArr = item.Split('(');
                        DataStrInfo data = new DataStrInfo();
                        data.Key = strArr[0];
                        data.Value = strArr[1].TrimEnd(')');
                        mruEditMaterial.Properties.Items.Add(data);
                        m_MaterialCrossDic.Add(data.Key, data.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "初始化实施配方信息异常：" + ex.Message);
            }    
        }

        private void InitProductLine()
        {
            try
            {
                string str = ConfigurationManager.AppSettings["ProductLines"].ToString();
                string[] productLineArr = str.Split(',');
                if (productLineArr.Length == 0)
                    return;
                mruEditProductLine.Properties.Items.Clear();
                foreach (string productLine in productLineArr)
                {
                    string[] strArr = productLine.Split('/');
                    DataInfo data = new DataInfo();
                    data.Id = Convert.ToInt64(strArr[0]);
                    data.Value = strArr[1];
                    mruEditProductLine.Properties.Items.Add(data);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化生产线下拉框数据异常：" + ex.Message);
            }
        }

        //查询
        private void btnSearch_Click(object sender, EventArgs e)
        {
            m_CurrentProdNo = this.txtOrderCode.Text.Trim();
            m_CurrentMaterial = this.mruEditMaterial.Text.Trim();
            m_CurrentProductline = this.mruEditProductLine.Text.Trim();
            m_Start = (DateTime)dateEditStart.EditValue;
            m_End = (DateTime)dateEditEnd.EditValue;
            if (!backgroundWorker.IsBusy)
                backgroundWorker.RunWorkerAsync();
        }

        //关闭
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 线程
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<ProductConsumeData> list = new List<ProductConsumeData>();
            try
            {
                DataTable dt = new DataTable();
                if (m_Type == 0 || m_Type == 1)
                {
                    string sql = "select * from  ConsumpMaterial  where 1 = 1 and Pdate > '" + m_Start.ToString("yyyy-MM-dd HH:mm:ss") 
                        + "' and Pdate < '" + m_End.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    if (!string.IsNullOrEmpty(m_CurrentProdNo))
                    {
                        sql += " and ProdNo in (select prodno from ProdMasterData where jobno = '" + m_CurrentProdNo + "')";
                    }
                    if (!string.IsNullOrEmpty(m_CurrentMaterial))
                    {
                        sql += " and MaterialName = '" + m_CurrentMaterial + "'";
                    }
                    if (!string.IsNullOrEmpty(m_CurrentProductline))
                    {
                        sql += " and ProductLine = '" + m_CurrentProductline + "'";
                    }

                    dt = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            ProductConsumeData data = new ProductConsumeData();

                            data.ProdNo = dr["ProdNo"] == DBNull.Value ? "" : dr["ProdNo"].ToString();
                            data.Batchno = dr["Batchno"] == DBNull.Value ? "" : dr["Batchno"].ToString();
                            data.MaterialName = dr["MaterialName"] == DBNull.Value ? "" : dr["MaterialName"].ToString();
                            data.MaterialType = dr["MaterialType"] == DBNull.Value ? "" : dr["MaterialType"].ToString();
                            data.MAcademic = dr["MAcademic"] == DBNull.Value ? 0 : decimal.Parse(dr["MAcademic"].ToString());
                            data.MDesign = dr["MDesign"] == DBNull.Value ? 0 : decimal.Parse(dr["MDesign"].ToString());
                            data.MAct = dr["MAct"] == DBNull.Value ? 0 : decimal.Parse(dr["MAct"].ToString());
                            data.BatchTime = dr["BatchTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["BatchTime"].ToString());
                            data.StoreNo = dr["StoreNo"] == DBNull.Value ? 0 : int.Parse(dr["StoreNo"].ToString());
                            data.Pdate = dr["Pdate"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["Pdate"].ToString());
                            data.ProductLine = dr["ProductLine"] == DBNull.Value ? "" : dr["ProductLine"].ToString();
                            data.RecipeValue = dr["RecipeValue"] == DBNull.Value ? 0 : decimal.Parse(dr["RecipeValue"].ToString());
                            data.BatchAdd = dr["BatchAdd"] == DBNull.Value ? 0 : decimal.Parse(dr["BatchAdd"].ToString());
                            list.Add(data);
                        }
                    }
                }
                else if (m_Type == 2)
                {
                    dt = ParadoxHelper.CreateInstance().DoSqlSelect("data", CreateSqlOfCB3800().ToArray());

                    List<string> columnList = new List<string>();
                    //如果过滤物料，则只需去一个值，反之将所有物料的消耗取出
                    if (!string.IsNullOrEmpty(m_CurrentMaterial))
                    {
                        foreach (string item in m_MaterialCrossDic.Keys)
                        {
                            if (m_MaterialCrossDic[item] == m_CurrentMaterial)
                            {
                                columnList.Add(item);
                                break;
                            }
                        }
                    }
                    else
                    {
                        foreach (string item in m_MaterialCrossDic.Keys)
                            columnList.Add(item);
                    }
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        var query = from temp in dt.AsEnumerable()
                                    where temp["Filehead"].ToString() == "2"
                                    group temp by new { Jobno = temp["Jobno"], Pl = temp["Pl"]} into result
                                    select new
                                    {
                                        result.Key.Jobno,
                                        result.Key.Pl,
                                        TotalDAD01 = result.Sum(temp => decimal.Parse(temp["DAD01"].ToString())),
                                        TotalDAD02 = result.Sum(temp => decimal.Parse(temp["DAD02"].ToString())),
                                        TotalDAD03 = result.Sum(temp => decimal.Parse(temp["DAD03"].ToString())),
                                        TotalDAD04 = result.Sum(temp => decimal.Parse(temp["DAD04"].ToString())),
                                        TotalDAD05 = result.Sum(temp => decimal.Parse(temp["DAD05"].ToString())),
                                        TotalDAD06 = result.Sum(temp => decimal.Parse(temp["DAD06"].ToString())),

                                        TotalDAC01 = result.Sum(temp => decimal.Parse(temp["DAC01"].ToString())),
                                        TotalDAC02 = result.Sum(temp => decimal.Parse(temp["DAC02"].ToString())),
                                        TotalDAC03 = result.Sum(temp => decimal.Parse(temp["DAC03"].ToString())),
                                        TotalDAC04 = result.Sum(temp => decimal.Parse(temp["DAC04"].ToString())),
                                        TotalDAC05 = result.Sum(temp => decimal.Parse(temp["DAC05"].ToString())),
                                        TotalDAC06 = result.Sum(temp => decimal.Parse(temp["DAC06"].ToString())),
                                        TotalDAC07 = result.Sum(temp => decimal.Parse(temp["DAC07"].ToString())),
                                        TotalDAC08 = result.Sum(temp => decimal.Parse(temp["DAC08"].ToString())),
                                        TotalDAC09 = result.Sum(temp => decimal.Parse(temp["DAC09"].ToString())),
                                        TotalDAC10 = result.Sum(temp => decimal.Parse(temp["DAC10"].ToString())),

                                        TotalDAB01 = result.Sum(temp => decimal.Parse(temp["DAB01"].ToString())),
                                        TotalDAB02 = result.Sum(temp => decimal.Parse(temp["DAB02"].ToString())),
                                        TotalDAB03 = result.Sum(temp => decimal.Parse(temp["DAB03"].ToString())),
                                        TotalDAB04 = result.Sum(temp => decimal.Parse(temp["DAB04"].ToString())),
                                        TotalDAB05 = result.Sum(temp => decimal.Parse(temp["DAB05"].ToString())),
                                        TotalDAB06 = result.Sum(temp => decimal.Parse(temp["DAB06"].ToString())),

                                        TotalDAA01 = result.Sum(temp => decimal.Parse(temp["DAA01"].ToString())),
                                        TotalDAA02 = result.Sum(temp => decimal.Parse(temp["DAA02"].ToString())),
                                        TotalDAA03 = result.Sum(temp => decimal.Parse(temp["DAA03"].ToString())),
                                        TotalDAA04 = result.Sum(temp => decimal.Parse(temp["DAA04"].ToString())),
                                        TotalDAA05 = result.Sum(temp => decimal.Parse(temp["DAA05"].ToString())),
                                        TotalDAA06 = result.Sum(temp => decimal.Parse(temp["DAA06"].ToString())),
                                        TotalDAA07 = result.Sum(temp => decimal.Parse(temp["DAA07"].ToString())),
                                    };

                        foreach (var item in query)
                        {
                            foreach (string column in columnList)
                            {
                                ProductConsumeData data = new ProductConsumeData();
                                data.ProdNo = item.Jobno.ToString();
                                data.MaterialName = m_MaterialCrossDic[column];
                                string newColumn = "Total" + column;

                                decimal value = 0;

                                Type type = item.GetType(); //获取类型
                                System.Reflection.PropertyInfo propertyInfo = type.GetProperty(newColumn); //获取指定名称的属性
                                decimal.TryParse(propertyInfo.GetValue(item, null).ToString(), out value);//获取属性值
                                data.MAct = value;
                                data.ProductLine = item.Pl.ToString();
                                list.Add(data);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            e.Result = list;
        }

        private List<string> CreateSqlOfCB3800()
        {
            List<string> sqlList = new List<string> ();
            //CB3800每天一张表，若分天需到多张表中去取
            int days = (m_End.Date - m_Start.Date).Days;
            for (int i = 0; i <= days; i++)
            {
                string sql = "select * from " + m_Start.Date.AddDays(i).ToString("yyyyMMdd")
                    + " where 1 = 1 " + " and time1 >= #" + m_Start.ToString("HH:mm:ss")
                    + "# and time1 <= #" + (days == 0 ? m_End.ToString("HH:mm:ss")
                    : m_Start.Date.AddDays(1).AddSeconds(-1).ToString("HH:mm:ss")) + "#";
                //如果当前订单号不为空，取后十位
                if (!string.IsNullOrEmpty(m_CurrentProdNo))
                {
                    sql += " and Jobno = '" + m_CurrentProdNo.Substring(m_CurrentProdNo.Length - 10) + "'";
                }
                //由于CB3800的物料是以列的形式存在，即横向结构，则取出后再过滤
                //如果生产线不为空
                if (!string.IsNullOrEmpty(m_CurrentProductline))
                {
                    sql += " and Pl = '" + m_CurrentProductline + "'";
                }
                sqlList.Add(sql);
            }
            return sqlList;
        }



        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                    return;
                if (e.Error != null)
                {
                    MessageBox.Show(this, e.Error.Message);
                    return;
                }
                m_BindDT.Clear();
                gdcConsume.DataSource = m_BindDT;
                List<ProductConsumeData> list = e.Result as List<ProductConsumeData>;
                if (list == null || list.Count == 0)
                    return;
                foreach (ProductConsumeData data in list)
                    m_BindDT.Rows.Add(data.ProdNo, data.Batchno, data.MaterialName, data.MaterialType, data.MAcademic, data.MDesign,
                        data.MAct, data.BatchTime, data.StoreNo, data.Pdate, data.ProductLine, data.RecipeValue, data.BatchAdd);
                gdcConsume.DataSource = m_BindDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定批量发货信息异常：" + ex.ToString());
            }
        }
        #endregion
    }
}
